<?php

//就近 www.jiujin.me
global $_W, $_GPC;
$operation = !empty($_GPC['op']) ? $_GPC['op'] : 'display';
if ($operation == 'display') {
	ca('package.list.view');
	$pindex = max(1, intval($_GPC['page']));
	$psize = 20;
	$list = pdo_fetchall("SELECT * FROM " . tablename('ewei_shop_package') . " WHERE uniacid = '{$_W['uniacid']}' ORDER BY id DESC LIMIT " . ($pindex - 1) * $psize . ',' . $psize);
	foreach($list as $key => $value){
		$list[$key]['lianjie'] = 'http://wx.lanxuevip.com/app/index.php?i=5&c=entry&do=package&m=ewei_shop&id='.$value['id'];
	}
	$total = pdo_fetchcolumn("SELECT * FROM " . tablename('ewei_shop_package') . " WHERE uniacid = '{$_W['uniacid']}' ORDER BY id DESC");
	$pager = pagination($total, $pindex, $psize);
} elseif ($operation == 'post') {
	$id = intval($_GPC['id']);
	if (empty($id)) {
		ca('package.list.add');
	} else {
		ca('package.list.edit|package.list.view');
	}
	if (checksubmit('submit')) {
		$data = array('uniacid' => $_W['uniacid'], 'type' => $_GPC['type'], 'title' => trim($_GPC['title']), 'content' => trim($_GPC['content']), 'money' => intval($_GPC['money']), 'link' => trim($_GPC['link']), 'status' => intval($_GPC['status']), 'createtime' => time(), 'goodsid' => intval($_GPC['goodsid']), 'goods' => trim($_GPC['goods']));
		$data['group'] = implode(',',$_GPC['group']);
		if (!empty($id)) {
			pdo_update('ewei_shop_package', $data, array('id' => $id));
			plog('package.list.edit', "修改套盒二维码 ID: {$id}");
		} else {
			pdo_insert('ewei_shop_package', $data);
			$id = pdo_insertid();
			plog('package.list.add', "修改套盒二维码 ID: {$id}");
		}
		message('更新套盒二维码成功！', $this->createWebUrl('package/list', array('op' => 'display')), 'success');
	}
	
	$package = pdo_fetch("SELECT * FROM " . tablename('ewei_shop_package') . " WHERE id = '{$id}' and uniacid = '{$_W['uniacid']}'");
	//$group = pdo_fetchall('SELECT groupid,title FROM ' . tablename('mc_groups') . " WHERE uniacid = '{$_W['uniacid']}' ");
	$group = pdo_fetchall('SELECT id,groupname FROM ' . tablename('ewei_shop_member_group') . " WHERE uniacid = '{$_W['uniacid']}' ");
	$grouparr = explode(',',$package['group']);
	foreach($group as &$g){
		if(empty($package['group'])){
			$g['groupid_select'] = 0;
		}else{
			if(in_array($g['id'], $grouparr)) {
				$g['groupid_select'] = 1;
			}
		}
	}
	if($id){
		$goods = pdo_fetch("SELECT thumb FROM " . tablename('ewei_shop_goods') . " WHERE id = '{$package['goodsid']}' and uniacid = '{$_W['uniacid']}'");
	}
} elseif ($operation == 'delete') {
	ca('package.list.delete');
	$id = intval($_GPC['id']);
	$package = pdo_fetch("SELECT id,title  FROM " . tablename('ewei_shop_package') . " WHERE id = '{$id}' AND uniacid=" . $_W['uniacid'] . "");
	if (empty($package)) {
		message('抱歉，该套盒不存在或已经被删除！', $this->createWebUrl('package/list', array('op' => 'display')), 'error');
	}
	pdo_delete('ewei_shop_package', array('id' => $id));
	plog('package.list.delete', "删除套盒二维码 ID: {$id} 标题: {$package['title']}");
	message('套盒二维码删除成功！', $this->createWebUrl('package/list', array('op' => 'display')), 'success');
}elseif ($operation == 'record' || $operation=='recordall') {
	$id = intval($_GPC['id']);
	
	if($id>0){
	//条件搜索
	$condition = "r.package = '{$id}' AND r.uniacid=" . $_W['uniacid'] ;
	}
	else {
		$condition = " r.uniacid=" . $_W['uniacid'] ;
		
	}
	
	if (!empty($_GPC['member'])) {
		$_GPC['member'] = trim($_GPC['member']);
		//$condition .= " AND (m.realname LIKE '%{$_GPC['member']}%' or m.mobile LIKE '%{$_GPC['member']}%' or m.nickname LIKE '%{$_GPC['member']}%' " . " or a.realname LIKE '%{$_GPC['member']}%' or a.mobile LIKE '%{$_GPC['member']}%' or o.carrier LIKE '%{$_GPC['member']}%')";
		$condition .= " AND ( r.nickname LIKE '%{$_GPC['member']}%' or m.realname LIKE '%{$_GPC['member']}%' or m.mobile LIKE '%{$_GPC['member']}%' or m.weixin LIKE '%{$_GPC['member']}%') ";
	}
	
	if (!empty($_GPC['time'])) {
		$starttime = strtotime($_GPC['time']['start']);
		$endtime = strtotime($_GPC['time']['end']);
		if ($_GPC['searchtime'] == '1') {
			$condition .= " AND r.createtime >= :starttime AND r.createtime <= :endtime ";
			$paras[':starttime'] = $starttime;
			$paras[':endtime'] = $endtime;
		}
	}
	
	//$record = pdo_fetchAll("SELECT *  FROM " . tablename('ewei_shop_package_record') . " m WHERE " . $condition . " order by id desc"); //仅微信昵称搜索  2016-05-24
	//$record = pdo_fetchall('SELECT pr.id,pr.createtime,pr.nickname,p.goods,p.type,p.money FROM ' . tablename('ewei_shop_package_record') . ' AS pr LEFT JOIN ' . tablename('ewei_shop_package') . ' AS p ON p.id = pr.package WHERE pr.uniacid = :uniacid AND pr.package=:package ORDER BY pr.id DESC', array(':uniacid' => $_W['uniacid'], ':package' => $id));
	
	$record = pdo_fetchAll("SELECT r.*, FROM_UNIXTIME(r.createtime,'%Y-%m-%d') as cdate,FROM_UNIXTIME(r.createtime,'%T') as ctime,m.createtime,m.avatar,m.realname,m.mobile,m.weixin  FROM " . tablename('ewei_shop_package_record') . " r left  join " . tablename('ewei_shop_member') . " m on r.uid=m.uid and r.uniacid=m.uniacid" . " WHERE " . $condition . " order by r.id desc", $paras);
	
	//echo("SELECT r.*,m.createtime,m.avatar,m.realname,m.mobile,m.weixin  FROM " . tablename('ewei_shop_package_record') . " r left  join " . tablename('ewei_shop_member') . " m on r.uid=m.uid and r.uniacid=m.uniacid" . " WHERE " . $condition . " order by r.id desc");
	
	foreach ($record as $key => $value){
		/*$member = pdo_fetch("SELECT *  FROM " . tablename('ewei_shop_member') . " WHERE uid =:uid AND uniacid=" . $_W['uniacid'] . "",array(':uid'=>$value['uid']));
		$record[$key]['createtime'] = date('Y-m-d H:i:s',$value['createtime']);
		$record[$key]['avatar'] = $member['avatar'];
		$record[$key]['realname'] = $member['realname'];
		$record[$key]['mobile'] = $member['mobile'];
		$record[$key]['weixin'] = $member['weixin'];*/
		$memberlevel = pdo_fetch("SELECT *  FROM " . tablename('ewei_shop_member_level') . " WHERE id =:id AND uniacid=" . $_W['uniacid'] . "",array(':id'=>$member['level']));
		$record[$key]['levelname'] = empty($memberlevel['levelname']) ? '普通会员' : $memberlevel['levelname'];
		$membergroup = pdo_fetch("SELECT *  FROM " . tablename('ewei_shop_member_group') . " WHERE id =:id AND uniacid=" . $_W['uniacid'] . "",array(':id'=>$member['groupid']));
		$record[$key]['groupname'] = empty($membergroup['groupname']) ? '无分组' : $membergroup['groupname'];
		
	}
	if ($_GPC['export'] == 1) {
		foreach ($record as $key => $value){
			$record[$key]['type'] = $value['type']==1?'蓝色(员工)':'红色(美容师)';
		}
		$columns = array(array('title' => 'uid', 'field' => 'uid', 'width' => 12), array('title' => '昵称', 'field' => 'nickname', 'width' => 12),  array('title' => '真实姓名', 'field' => 'realname', 'width' => 12),  array('title' => '联系方式', 'field' => 'mobile', 'width' => 12), array('title' => '微信号', 'field' => 'weixin', 'width' => 12), array('title' => '会员等级', 'field' => 'levelname', 'width' => 12), array('title' => '会员分组', 'field' => 'groupname', 'width' => 12), array('title' => '套盒ID', 'field' => 'package', 'width' => 12), array('title' => '类型', 'field' => 'type', 'width' => 12), array('title' => '奖励余额', 'field' => 'money', 'width' => 12), array('title' => "关联商品", 'field' => 'goods', 'width' => 24), array('title' => "扫码时间", 'field' => 'createtime', 'width' => 24));
		m('excel')->export($record, array("title" => "套盒扫码导出" . date('Y-m-d-H-i', time()), "columns" => $columns));
	}
}elseif ($operation == 'qrcode'){
	$id = $_GPC['id'];
	//$color = $_GPC['color']?$_GPC['color']:'';
	$jumpurl = 'http://wx.lanxuevip.com/app/index.php?i=5&c=entry&do=package&m=ewei_shop&id='.$id;
	$time = time();
	$package = pdo_fetch("SELECT type FROM " . tablename('ewei_shop_package') . " WHERE id = '{$id}' and uniacid = '{$_W['uniacid']}'");
	if (checksubmit('submit')) {
		$endtime = strtotime($_GPC['endtime']);
		$path = IA_ROOT . "/addons/ewei_shop/data/package/" . $_W['uniacid'] . "/";
		if (!is_dir($path)) {
			load()->func('file');
			mkdirs($path);
		}
		$barcode = array(
			'expire_seconds' => '',
			'action_name' => '',
			'action_info' => array(
				'scene' => array(),
			),
		);
		$acid = intval($_W['acid']);
		$uniacccount = WeAccount::create($acid);
		
		if($_GPC['id'] == ''){
			message('抱歉，没有该套盒二维码！', $this->createWebUrl('package/list', array('op' => 'display')), 'error');
		}
		//生成二维码的颜色 红色 FF0000 蓝色 0000ff
		if($package['type'] == 1){
			$color = 1;
		}else{
			$color = 2;
		}
		//只生成一遍即可
		//ims_rule
		$rule = array(
			'uniacid' 	   => $_W['uniacid'],
			'name'	       => $_GPC['name'],
			'module'       => 'news',
			'displayorder' => 0,
			'status'	   => 1
		);
		pdo_insert('rule', $rule);
		$rid = pdo_insertid();
		//ims_rule_keyword
		$rulekeyword = array(
			'rid'	  	   => $rid,
			'uniacid' 	   => $_W['uniacid'],
			'module'  	   => 'news',
			'content' 	   => $_GPC['keyword'],
			'type'	  	   => 1,
			'displayorder' => 0,
			'status'	   => 1
		);
		pdo_insert('rule_keyword', $rulekeyword);
		//ims_news_reply
		$newsreply = array(
			'rid'	  	   => $rid,
			'parentid' 	   => 0,
			'title'  	   => $_GPC['title'],
			'description'  => $_GPC['description'],
			'thumb'		   => $_GPC['thumb'],
			'content' 	   => '',
			'url'	  	   => $jumpurl,
			'displayorder' => 0,
			'incontent'	   => 1,
			'author'	   => '',
			'createtime'   => TIMESTAMP
		);
		pdo_insert('news_reply', $newsreply);
		//批量加入数据库
		$number = intval($_GPC['number']);
		/*
		for($i=1;$i<=$number;$i++){
			//ims_qrcode
			$qrctype = intval($_GPC['qrc-model']);
			if ($qrctype == 1) {
				$qrcid = pdo_fetchcolumn("SELECT qrcid FROM ".tablename('qrcode')." WHERE acid = :acid AND model = '1' ORDER BY qrcid DESC LIMIT 1", array(':acid' => $acid));
				$barcode['action_info']['scene']['scene_id'] = !empty($qrcid) ? ($qrcid+1) : 100001;
				$during = strtotime($_GPC['time']['end']) - strtotime($_GPC['time']['start']);
				$barcode['expire_seconds'] = intval($during);
				$barcode['action_name'] = 'QR_SCENE';
				$result = $uniacccount->barCodeCreateDisposable($barcode);
			} else if ($qrctype == 2) {
				$scene_str = trim($_GPC['scene_str']);
				if(!empty($scene_str)) {
					$barcode['action_info']['scene']['scene_str'] = $scene_str;
					$barcode['action_name'] = 'QR_LIMIT_STR_SCENE';
				} else {
					$qrcid = pdo_fetchcolumn("SELECT qrcid FROM ".tablename('qrcode')." WHERE acid = :acid AND model = '2' ORDER BY qrcid DESC LIMIT 1", array(':acid' => $acid));
					$barcode['action_info']['scene']['scene_id'] = !empty($qrcid) ? ($qrcid+1) : 1;
					if ($barcode['action_info']['scene']['scene_id'] > 100000) {
						message('抱歉，永久二维码已经生成最大数量，请先删除一些。');
					}
					$barcode['action_name'] = 'QR_LIMIT_SCENE';
				}
				$result = $uniacccount->barCodeCreateFixed($barcode);
			}else {
				message('抱歉，此公众号暂不支持您请求的二维码类型！');
			}
			
			if(!is_error($result)) {
				$insert = array(
					'uniacid' => $_W['uniacid'],
					'acid' => $acid,
					'qrcid' => $barcode['action_info']['scene']['scene_id'],
					'scene_str' => $barcode['action_info']['scene']['scene_str'],
					'keyword' => $_GPC['keyword'],
					'name' => $_GPC['title'],
					'model' => $_GPC['qrc-model'],
					'ticket' => $result['ticket'],
					'url' => $result['url'],
					'expire' => $result['expire_seconds'],
					'createtime' => TIMESTAMP,
					'status' => '1',
					'type' => 'scene',
					'special' => '1'		//代表着只能扫一次
				);
				pdo_insert('qrcode', $insert);
			} else {
				message("公众平台返回接口错误. <br />错误代码为: {$result['errorcode']} <br />错误信息为: {$result['message']}");
			}
			//保存图片到data里
			$img = file_get_contents('https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='.$result['ticket']); 
			file_put_contents($path.$i.'.png',$img);
		}*/
		
		require IA_ROOT . '/framework/library/qrcode/phpqrcodecolor.php';
		for($i=1;$i<=$number;$i++){
			//---------- 开始
			$file = $i . '.png';
			$qr_file = $path . $file;
			//再加上2个参数
			$jumpurl = 'http://wx.lanxuevip.com/app/index.php?i=5&c=entry&do=package&m=ewei_shop&id='.$id;
			$jumpurl = $jumpurl . '&dist=' .$i . '&endtime=' . $endtime . '&downsn=' .$time;
			//QRcode::png($jumpurl, $qr_file, QR_ECLEVEL_H, 4);
			QRcode::png($jumpurl, $qr_file, 'L', 8, 4, false, $color);		//红色 FF0000 蓝色 0000ff
				
			//---------- 结束
			//ims_qrcode
			/*
			$qrcid = pdo_fetchcolumn("SELECT qrcid FROM ".tablename('qrcode')." WHERE acid = :acid AND model = '1' ORDER BY qrcid DESC LIMIT 1", array(':acid' => $acid));
			$scene_id = !empty($qrcid) ? ($qrcid+1) : 100001;
			$insert = array(
				'uniacid' => $_W['uniacid'],
				'acid' => $acid,
				'qrcid' => $scene_id,
				'scene_str' => '',
				'keyword' => $_GPC['keyword'],
				'name' => $_GPC['title'],
				'model' => $_GPC['qrc-model'],
				'ticket' => '',
				'url' => '',
				'expire' => '',
				'createtime' => TIMESTAMP,
				'status' => '1',
				'type' => 'scene',
				'special' => '1'		//代表着只能扫一次
			);
			pdo_insert('qrcode', $insert);
			*/
			//保存图片到data里
			$img = file_get_contents($_W['siteroot'] . 'addons/ewei_shop/data/package/' . $_W['uniacid'] . '/' . $file);
			file_put_contents($path.$i.'.png',$img);
		}
		//压缩
		$zip=new ZipArchive();
		if($zip->open(IA_ROOT . '/addons/ewei_shop/data/package/'.$_W['uniacid'].'/'.$time.'.rar',ZipArchive::OVERWRITE)===TRUE){
			//批量压缩
			for($i=1;$i<=$number;$i++){
				$zip->addFile(IA_ROOT . '/addons/ewei_shop/data/package/'.$_W['uniacid'].'/'.$i.'.png');
			}
		}
		$zip->close();
		
		//ims_ewei_shop_download
		$downld = array(
			'name'	  	 => $time.'.rar',
			'createtime' => TIMESTAMP,
			'uniacid'  	 => $_W['uniacid'],
			'type'  	 => 5,
			'endtime'    => $endtime
		);
		pdo_insert('ewei_shop_download', $downld);
			
		plog('package.list.qrcode', "批量生成二维码 ID 成功: {$id}");
		message('批量生成二维码成功！', $this->createWebUrl('package/list', array('op' => 'display')), 'success');
	} 
} elseif ($operation == 'download') {
	ca('package.list.view');
	$pindex = max(1, intval($_GPC['page']));
	$psize = 20;
	$list = pdo_fetchall("SELECT * FROM " . tablename('ewei_shop_download') . " WHERE uniacid = '{$_W['uniacid']}' AND type = 5 ORDER BY id DESC LIMIT " . ($pindex - 1) * $psize . ',' . $psize);
	foreach($list as $key => $value){
		$list[$key]['createtime'] = date('Y-m-d H:i:s',$value['createtime']);
		$list[$key]['downlink'] = 'http://wx.lanxuevip.com/addons/ewei_shop/data/package/'.$_W['uniacid'].'/'.$value['name'];
		$list[$key]['deletelink'] = $this->createWebUrl('package/list', array('op' => 'downloaddelete', 'id' => $value['id']));
	}
	$total = pdo_fetchcolumn("SELECT count(*) FROM " . tablename('ewei_shop_download') . " WHERE uniacid = '{$_W['uniacid']}' AND type = 5 ORDER BY id DESC");
	$pager = pagination($total, $pindex, $psize);
} elseif ($operation == 'downloaddelete') {
	ca('package.list.downloaddelete');
	$id = intval($_GPC['id']);
	$data = pdo_fetch("SELECT id,name FROM " . tablename('ewei_shop_download') . " WHERE id = '{$id}' AND type = 5 AND uniacid=" . $_W['uniacid'] . "");
	if (empty($data)) {
		message('抱歉，该压缩包不存在或是已经被删除！', $this->createWebUrl('package/list', array('op' => 'display')), 'error');
	}
	pdo_delete('ewei_shop_download', array('id' => $id));
	unlink(IA_ROOT . '/addons/ewei_shop/data/package/'.$_W['uniacid'].'/'.$data['name']);
	plog('package.list.downloaddelete', "删除压缩包 ID: {$id} 标题: {$data['name']}");
	message('压缩包删除成功！', $this->createWebUrl('package/list', array('op' => 'display')), 'success');
}

load()->func('tpl');
include $this->template('web/package/list');